﻿using System;
using System.IO;
using System.Threading;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ICSharpCode.SharpZipLib.Zip;
using MyWebPagesStarterKit;
using MyWebPagesStarterKit.Controls;

public partial class Administration_Backup : PageBaseClass
{
        public static string message = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            BindData();
        }

        public void ZipIt(string Path, string outPathAndZipFile, string password)
        {
            string OutPath = outPathAndZipFile;
            ArrayList ar = GenerateFileList(Path);
            // generate file list   
            // find number of chars to remove from orginal file path   
            int TrimLength = (Directory.GetParent(Path)).ToString().Length;
            TrimLength += 1; //remove '\'   
            FileStream ostream;
            byte[] obuffer;
            ZipOutputStream oZipStream = new ZipOutputStream(System.IO.File.Create(OutPath));
            // create zip stream   
            if (password != String.Empty)
                oZipStream.Password = password;

            oZipStream.SetLevel(9); // 9 = maximum compression level   
            ZipEntry oZipEntry;

            // for each file, generate a zipentry 
            foreach (string Fil in ar)
            {
                oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
                oZipStream.PutNextEntry(oZipEntry);
                if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory    
                {
                    ostream = File.OpenRead(Fil);
                    obuffer = new byte[ostream.Length]; // byte buffer     
                    ostream.Read(obuffer, 0, obuffer.Length);
                    oZipStream.Write(obuffer, 0, obuffer.Length);
                    Console.Write(".");
                }
            }
            
            oZipStream.Finish();
            oZipStream.Close();
            BindData();
        }

        private static System.Collections.ArrayList GenerateFileList(string Dir)
        {
            ArrayList mid = new ArrayList();
            bool Empty = true;
            foreach (string file in Directory.GetFiles(Dir)) // add each file in directory   
            {
                mid.Add(file);
                Empty = false;
            }
            if (Empty)
            {
                if (Directory.GetDirectories(Dir).Length == 0)
                // if directory is completely empty, add it    
                {
                    mid.Add(Dir + @"/");
                }
            }
            foreach (string dirs in Directory.GetDirectories(Dir)) // do this recursively   
            {
                // set up the excludeDir test    
                string testDir = dirs.Substring(dirs.LastIndexOf(@"\") + 1).ToUpper();
                
                    //if(Backup.excludeDirs.Contains(testDir))    
                    //continue;    
                    foreach (object obj in GenerateFileList(dirs))
                    { 
                        mid.Add(obj); 
                    }
               
            } return mid; // return file list  
        }

        private void listZip()
        {
            string list = "";
            string path = Request.PhysicalApplicationPath + "~/App_Data/Backup";
            ArrayList zipfiles = GenerateFileListZip(path);
            foreach (string file in zipfiles)
            {
                if (file.EndsWith(".zip"))
                {
                    list += "<a href=\"handlers/Attachements.ashx?file=" + Path.GetFileName(file) + "\">" + Path.GetFileName(file) + "</a><br>";
                }
            }
            fileList.Text = list;
        }


        protected void gwItem_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "delete_item")
            {
                string filename = "~/App_Data/Backup/" + gwFiles.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString();
                File.Delete(Server.MapPath(filename));
                //Response.Write(filename);
                BindData();
            }
        }

        private void BindData()
        {
           if (!Directory.Exists(Server.MapPath("~/App_Data/Backup")))
               Directory.CreateDirectory(Server.MapPath("~/App_Data/Backup"));

            gwFiles.DataSource = null;

            List<Item> files = new List<Item>();
            string path = "~/App_Data/Backup";
            foreach (string file in Directory.GetFiles(Server.MapPath(path)))
            {
                string[] fname = file.Split(new char[]{'_'});
                Item itm = new Item(file.Substring(file.LastIndexOf("\\")+1), fname[1]);
                files.Add(itm);
            }
            files.Sort();
            files.Reverse();
            gwFiles.DataSource = files;
            gwFiles.DataBind();
            
        }

        public class Item : IComparable
        {
            private string _Name;
            private string _Created;
            public Item(string name, string created)
            {
                this._Name = name;
                this._Created = created;
            }

            public int CompareTo(object obj)
            {
                if (obj is Item)
                {
                    Item p2 = (Item)obj;
                    return _Name.CompareTo(p2.Name);
                }
                else
                    throw new ArgumentException("Object is not a Name.");
            }

            public string Name
            {
                get { return _Name; }
                set { _Name = value; }
            }

            public string Created
            {
                get { return _Created; }
                set { _Created = value; }
            }
        }

        private static System.Collections.ArrayList GenerateFileListZip(string Dir)
        {
            ArrayList mid = new ArrayList();
            bool Empty = true;
            foreach (string file in Directory.GetFiles(Dir)) // add each file in directory   
            {
                mid.Add(file);
                Empty = false;
            }
            if (Empty)
            {
                if (Directory.GetDirectories(Dir).Length == 0)
                // if directory is completely empty, add it    
                {
                    mid.Add(Dir + @"/");
                }
            }
            foreach (string dirs in Directory.GetDirectories(Dir)) // do this recursively   
            {    // set up the excludeDir test    
                string testDir = dirs.Substring(dirs.LastIndexOf(@"\") + 1).ToUpper();
                //if(Backup.excludeDirs.Contains(testDir))    
                //  continue;    
                foreach (object obj in GenerateFileListZip(dirs))
                {
                    mid.Add(obj);
                }
            }
            return mid; // return file list  
        }



        public void backupData()
        {
            try
            {
                if (!Directory.Exists(Server.MapPath("~/App_Data/Backup")))
                    Directory.CreateDirectory(Server.MapPath("~/App_Data/Backup"));


                string time = Convert.ToString(DateTime.Now).Replace(":", "").Replace(" ","").Replace("\\","").Replace("/","");

                string path = Request.PhysicalApplicationPath + "App_Data";
                string file = Request.PhysicalApplicationPath + @"App_Data\Backup\" + time + ".zip";
                string pass = txtPassword.Text;

                ZipIt(path, file, pass);
                
            }
            catch{}
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            backupData();
        }
}
